package com.ittest.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class RedisDynamicKeyService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 固定前缀和中间部分
    private static final String FIXED_PREFIX = "F_ATHENA_SUPERCELL_BETANOAH:v2_1:sc_p_c";
    private static final String FIXED_MIDDLE = "commonBoostBargainProcess";

    /**
     * 根据动态参数构建完整的key
     */
    public String buildKey(String pagecode, String activitycode, String username) {
        // 拼接格式：固定前缀 + pagecode + : + activitycode + : + 固定中间部分 + : + username
        return String.join(":",
                FIXED_PREFIX,
                pagecode,
                activitycode,
                FIXED_MIDDLE,
                username);
    }

    /**
     * 根据动态参数删除匹配的key
     */
    public int deleteByDynamicParams(String pagecode, String activitycode, String username) {
        // 构建完整的 key（精确匹配）
        String fullKey = buildKey(pagecode, activitycode, username);

        int deletedCount = 0;

        // 获取 Redis 连接（自动归还连接池）
        try (RedisConnection connection = stringRedisTemplate.getConnectionFactory().getConnection()) {
            // 配置 SCAN 参数（精确匹配完整 key）
            ScanOptions options = ScanOptions.scanOptions()
                    .match(fullKey) // 精确匹配，无需通配符
                    .count(10) // 少量匹配，count 设小一点
                    .build();

            // 执行 SCAN 命令
            Cursor<byte[]> cursor = connection.scan(options);

            // 收集并删除匹配的 key
            List<byte[]> keys = new ArrayList<>();
            while (cursor.hasNext()) {
                keys.add(cursor.next());
            }

            // 批量删除（实际只会有 0 或 1 个 key）
            if (!keys.isEmpty()) {
                connection.del(keys.toArray(new byte[0][]));
                deletedCount = keys.size();
            }

            cursor.close();
        }

        return deletedCount;
    }
}